import 'package:dio/dio.dart';
import 'package:xim/http/http.dart';
import 'package:xim/http/store.dart';
import 'package:xim/widget/dash_chat_2/dash_chat_2.dart';

/// 好友模型 [java:UserFriendRespVo]
class UserFriendModel {

  /// 关系ID(PK)
  int id;

  /// 状态：1-正常，2-待同意
  int status;

  /// 好友备注
  String? friendNote;

  /// 好友申请时候的描述信息
  String? applyNote;

  /// 用户账号
  String userAccount;

  /// 创建时间
  DateTime createTime;

  /// 创建者账号
  String creatorAccount;

  /// 申请来源：1-qr,2-search
  int? applySourceType;

  /// 是否已读
   bool hasRead;

  /// 好友信息
  UserInfoModel friendUserInfo;

  UserFriendModel(
      this.id,
      this.status,
      this.userAccount,
      this.creatorAccount,
      this.applySourceType,
      {
        this.applyNote,
        this.friendNote,
        required this.friendUserInfo,
        required this.createTime,
        required this.hasRead
      });

  Map<String, dynamic> toJson() => {
        "id": id,
        "status": status,
        "friendNote": friendNote,
        "applyNote": applyNote,
        "applySourceType": applySourceType,
        "userAccount": userAccount,
        "creatorAccount": creatorAccount,
        "friendUserInfo": friendUserInfo.toJson(),
        "createTime": createTime,
        "hasRead": hasRead,
      };

  UserFriendModel.fromJson(Map<String, dynamic> jsonMap)
      : id = jsonMap['id'],
        status = jsonMap['status'],
        friendNote = jsonMap['friendNote'],
        applyNote = jsonMap['applyNote'],
        userAccount = jsonMap['userAccount'],
        creatorAccount = jsonMap['creatorAccount'],
        applySourceType = jsonMap['applySourceType'],
        friendUserInfo = UserInfoModel.fromJson(jsonMap['friendUserInfo']),
        createTime = DateTime.parse(jsonMap['createTime']),
        hasRead = jsonMap['hasRead']
  ;

  /// 获取所有好友列表
  Future<List<UserFriendModel>> requestByAccount(String account) async {
    var result = await dio.postResult("/user/friend/query/list", cached: true);
    var data = result.data as List<dynamic>;
    return data.map((e) => UserFriendModel.fromJson(e)).toList();
  }

  /// 获取已经添加了的好友
  Future<List<UserFriendModel>> requestAgreementFriends(String account) async {
    var friends = await requestByAccount(account);
    return friends.where((element) => element.status==1).toList();
  }

}

/// 用户模型[java:UserInfoVo]
class UserInfoModel {

  /// 用户Id（唯一）
  final int id;

  /// 用户账号（唯一）
  final String account;

  /// 用户头像
  final String avatar;

  /// 用户公钥地址
  final String? publicKey;

  /// 用户名称
  final String name;

  UserInfoModel(this.id, this.account, this.avatar, this.publicKey, this.name);

  Map<String, dynamic> toJson() => {
        "id": id,
        "account": account,
        "avatar": avatar,
        "publicKey": publicKey,
        "name": name,
      };

  UserInfoModel.fromJson(Map<String, dynamic> jsonMap)
      : id = jsonMap['id'],
        account = jsonMap['account'],
        avatar = jsonMap['avatar'],
        publicKey = jsonMap['publicKey'],
        name = jsonMap['name'];

  /// bind api
  static Future<UserInfoModel?> requestByAccount(String account,
      {void Function(Response resp)? onError}) async {
    Options options = Options().addHeader('cached', true);
    var resp =
        await dio.get("/user/query/info", queryParameters: {"account": account}, options: options);
    // 错误处理
    if (resp.statusCode != 200 || resp.data['code'] != 0) {
      onError?.call(resp);
      return null;
    }
    // 解析
    return UserInfoModel.fromJson(resp.data['data']);
  }

  /// 类型转换
  ChatUser toChatUser(){
    return ChatUser(
      id: id.toString(),
      profileImage: avatar,
      customProperties: {
        "account": account,
        "publicKey": publicKey,
      },
      firstName: name,
    );
  }

}

extension ChatUserExtension on ChatUser{
  String? get account => customProperties!=null
      ? customProperties!['account']
      : null;

}